import {GameEngine} from "./gameEngine";
import {MyPlane} from "./myPlane"

export class Bullets {
  public id:number;
  public el:HTMLDivElement;
  public timer: number = 0;
  constructor() {
     this.id = parseInt(Math.random()*100000+"");
     this.el = document.createElement("div");
     this.el.className = "bullet";

     GameEngine.instance().el.appendChild(this.el);
     GameEngine.instance().bullets[Number(this.id)] = this;

     //设置出生位置
     let bX = MyPlane.instance().el.offsetLeft+MyPlane.instance().el.offsetWidth/2;
     let bY = MyPlane.instance().el.offsetTop;

     this.el.style.left = bX -4 + "px";
     this.el.style.top = bY - 10 + "px";

     this.move();
  }

  move() {
    this.timer = setInterval(()=>{
      this.el.style.top = this.el.offsetTop - 5 + "px";
      if(this.el.offsetTop <= 0) {
        clearInterval(this.timer);
        this.boom();
      }
    })
  }

  boom() {
    this.el.className = "bullet-die";
    let num = 0;
    let timer = setInterval(() => {
      num++;
      this.el.style.backgroundImage = `url(../images/die${num}.png)`;
      if(num >= 2) {
        clearInterval(timer);
        this.remove();
      }
    },100);
  }

  remove () {
    GameEngine.instance().bullets.splice(this.id,1);
    this.el.remove();
  }
}